﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.IO;
using System.Text;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using CrystalDecisions.CrystalReports;
using System.Globalization;



namespace BSC_OTC_Management.Forms
{
    public partial class FrmCreateReport : Form
    {


        #region Khai bao tham so chung

        Boolean DEBUG = false;

        Code.CL_Ultility cl_u = new Code.CL_Ultility();
        Code.StaticVariable _code = new Code.StaticVariable();
        DataTable TBL_RePortFLD = new DataTable("FLDvalue");
        string _formName = "BSC_TBL_RPTFIELDS";
        static string v_strRptID;

        public string GET_RPTID
        {
            get { return v_strRptID; }
            set { v_strRptID = value; }
        }

        public object check_null(string v_In)
        {
            try
            {
                if (v_In == null)
                {
                    return "";
                }
                else
                {
                    return v_In;
                }
            }
            catch (Exception ex)
            {
                return "";
            }
        }

        public string check_null2(object v_In)
        {
            try
            {
                if (v_In == null)
                {
                    return "";
                }
                else
                {
                    return v_In.ToString();
                }
            }
            catch (Exception ex)
            {
                return "";
            }
        }


        #endregion

        public FrmCreateReport()
        {
            InitializeComponent();
        }

        private void FrmCreateReport_Load(object sender, EventArgs e)
        {
            try
            {
                this.Text = GET_RPTID;

                Load_filed_Report();
                Giao_dien_Cau_hoi();
            }
            catch (Exception ex)
            {
                _code._services.UPDATE_LOG_FILE("ERR", Code.StaticVariable.userID, "Forms.FrmCreateReport", "FrmCreateReport_Load()", ex.ToString());

            }
        }

        public void Load_filed_Report()
        {
            try
            {


                string v_strDK = GET_RPTID;

                string v_strCMD = "Select objname, fldname,caption,datatype ,fldlen,llist,defval,searchcode,lookup,lookupname, odrnum From BSC_TBL_RPTFIELDS " + "where objname ='" + v_strDK + "' and visible = 'Y' order by odrnum asc ";

                DataTable v_tbl_ReportList = _code._services.GetDatatable_BySQL(v_strCMD);

                gridControl1.DataSource = v_tbl_ReportList;

                int l = v_tbl_ReportList.Rows.Count;

                // Nen dua vao tham so -----------
                int V_Top_Curr = 10;
                int v_NCanhleTrai_Cauhoi = 20;
                //------------------------------------------

                string v_objname = "";
                string v_fldname = "";
                string v_caption = "";
                string v_datatype = "";
                string v_llist = "";
                string v_defval = "";
                string v_lookup = "";
                string v_lookupname = "";

                int v_fldlen = 0;
                this.Panel_Add_Control.Controls.Clear();
                for (int i = 0; i <= l - 1; i++)
                {
                    v_objname = v_tbl_ReportList.Rows[i]["objname"].ToString();
                    v_fldname = v_tbl_ReportList.Rows[i]["fldname"].ToString();

                    v_caption = check_null2(v_tbl_ReportList.Rows[i]["caption"]);
                    v_datatype = check_null2(v_tbl_ReportList.Rows[i]["datatype"]);
                    v_llist = check_null2(v_tbl_ReportList.Rows[i]["llist"]);
                    v_fldlen = Convert.ToInt32(check_null2(v_tbl_ReportList.Rows[i]["fldlen"]));
                    v_defval = check_null2(v_tbl_ReportList.Rows[i]["defval"]);
                    v_lookup = check_null2(v_tbl_ReportList.Rows[i]["lookup"]);
                    v_lookupname = check_null2(v_tbl_ReportList.Rows[i]["lookupname"]);

                    //  v_objRptParam.ParamName = v_fldname;

                    System.Windows.Forms.Label Lbl_Cauhoi = new System.Windows.Forms.Label();
                    Lbl_Cauhoi.MaximumSize = new Size(1100, 0);
                    Lbl_Cauhoi.AutoSize = true;
                    Lbl_Cauhoi.Name = "lbl_" + v_fldname;
                    Lbl_Cauhoi.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(0));
                    Lbl_Cauhoi.ForeColor = System.Drawing.Color.Navy;
                    Lbl_Cauhoi.Top = V_Top_Curr;
                    Lbl_Cauhoi.Left = v_NCanhleTrai_Cauhoi;
                    Lbl_Cauhoi.Text = v_caption.Trim();
                    this.Panel_Add_Control.Controls.Add(Lbl_Cauhoi);

                    int v_right = Lbl_Cauhoi.Width;

                    switch (v_datatype)
                    {
                        case "T":
                            System.Windows.Forms.TextBox txt_Field = new System.Windows.Forms.TextBox();
                            txt_Field.Width = v_fldlen;
                            txt_Field.Name = "TXT#" + v_fldname;
                            txt_Field.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(0));
                            txt_Field.ForeColor = System.Drawing.Color.Navy;
                            txt_Field.Top = V_Top_Curr;
                            txt_Field.Text = "ALL";
                            txt_Field.Left = Lbl_Cauhoi.Width + 20 + 10;
                            if (v_lookup == "Y" && v_lookupname != "")
                            {
                                txt_Field.BackColor = Color.FromArgb(192, 255, 192);
                                txt_Field.AccessibleDescription = v_lookupname;
                                txt_Field.KeyDown += new KeyEventHandler(_textbox_KeyDown);
                            }
                            this.Panel_Add_Control.Controls.Add(txt_Field);
                            TBL_RePortFLD.Columns.Add(v_fldname);

                            //   v_objRptParam.ParamType = "VARCHAR2";
                            break;
                        case "D":
                            DateTimePicker dtp_Field = new DateTimePicker();
                            dtp_Field.Width = v_fldlen;
                            dtp_Field.Name = "DTP#" + v_fldname;
                            dtp_Field.CustomFormat = "dd/MM/yyyy";
                            dtp_Field.Format = DateTimePickerFormat.Custom;
                            dtp_Field.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(0));
                            dtp_Field.ForeColor = System.Drawing.Color.Navy;
                            dtp_Field.Top = V_Top_Curr;
                            // txt_Field.Text = "ALL"
                            dtp_Field.Left = Lbl_Cauhoi.Width + 20 + 10;
                            this.Panel_Add_Control.Controls.Add(dtp_Field);
                            TBL_RePortFLD.Columns.Add(v_fldname);
                            // v_objRptParam.ParamType = "DATE";
                            break;
                        case "C":
                            System.Windows.Forms.ComboBox cbb_Field = new System.Windows.Forms.ComboBox();
                            cbb_Field.Width = v_fldlen;
                            cbb_Field.Name = "CBB#" + v_fldname;
                            cbb_Field.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(0));
                            cbb_Field.ForeColor = System.Drawing.Color.Navy;
                            cbb_Field.Top = V_Top_Curr;
                            cbb_Field.Text = "ALL";
                            cbb_Field.Left = Lbl_Cauhoi.Width + 20 + 10;

                            //add items
                            DataTable _tableAllCode = _code._services.GetDatatable_BySQL(v_llist);
                            if (!v_llist.ToLower().Contains("allcode"))
                            {
                                cbb_Field.AccessibleName = "";
                            }
                            else
                            {
                                cbb_Field.AccessibleName = v_llist;
                            }
                            foreach (DataRow rowAllCode in _tableAllCode.Rows)
                            {
                                cbb_Field.Items.Add(rowAllCode["display"].ToString());
                            }
                            cbb_Field.SelectedIndex = 0;
                            cbb_Field.DropDownStyle = ComboBoxStyle.DropDownList;
                            //
                            this.Panel_Add_Control.Controls.Add(cbb_Field);
                            TBL_RePortFLD.Columns.Add(v_fldname); 

                            //  v_objRptParam.ParamType = "VARCHAR2";
                            break;
                    }



                    //V_Top_Curr += int.Parse(this.ComboBox_In.Text);
                    V_Top_Curr += 30;
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        // sự kiện F5 cho textbox gọi form truy vấn
        void _textbox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F5)
            {
                TextBox _textbox = sender as TextBox;
                //lấy thông tin truy vấn: tên bảng, title
                string tblname = _textbox.AccessibleDescription.ToString().Split('^')[2];
                DataTable menu = _code._services.GetMenu_ByMenuName(tblname);
                string tbltitle = "";
                if (menu.Rows.Count > 0)
                    tbltitle = menu.Rows[0]["menufullname"].ToString();

                Forms.FrmView _FrmView = new Forms.FrmView(tblname, tbltitle, true);
                _FrmView.ShowDialog();
                if (Code.StaticVariable.DTable.Rows.Count > 0)
                {
                    _textbox.Text = Code.StaticVariable.DTable.Rows[0][_textbox.AccessibleDescription.ToString().Split('^')[0]].ToString();
                    //_textbox.Name = Code.StaticVariable.DTable.Rows[0][_textbox.AccessibleDefaultActionDescription.ToString().Split('^')[0]].ToString();
                }
                Code.StaticVariable.DTable.Clear();
            }
        }

        public void Giao_dien_Cau_hoi()
        {
            try
            {

                int l = this.Panel_Add_Control.Controls.Count;
                int v_intMax = 0;
                //Cbb_Xemlai_ Lbl_Cauhoi_ Cbb_TraLoi_
                for (int i = 0; i <= l - 1; i++)
                {

                    if (this.Panel_Add_Control.Controls[i].GetType().ToString() == "System.Windows.Forms.Label")
                    {
                        //System.Windows.Forms.Label cbb_a = null;
                        //cbb_a = Panel_Add_Control.Controls[i].wi
                        int v_intK = Panel_Add_Control.Controls[i].Width;
                        if (v_intK > v_intMax)
                        {
                            v_intMax = v_intK;
                        }
                    }
                }

                for (int i = 0; i <= l - 1; i++)
                {

                    string v_strTypeName = this.Panel_Add_Control.Controls[i].GetType().ToString();
                    switch (v_strTypeName)
                    {
                        case "System.Windows.Forms.TextBox": //TXT#"

                            this.Panel_Add_Control.Controls[i].Left = v_intMax + 20 + 10;
                            break;
                        case "System.Windows.Forms.ComboBox": //DTP#

                            this.Panel_Add_Control.Controls[i].Left = v_intMax + 20 + 10;
                            break;
                        case "System.Windows.Forms.DateTimePicker": //CBB#

                            this.Panel_Add_Control.Controls[i].Left = v_intMax + 20 + 10;
                            break;
                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, " Giao_dien_Cau_hoi()");
            }
        }

        public Boolean BUIL_FLD_BAO_CAO()
        {
            try
            {
                DataRow rowValue = TBL_RePortFLD.NewRow();
                DataRow rowDataType = TBL_RePortFLD.NewRow();
                TBL_RePortFLD.Rows.Clear();

                int l = this.Panel_Add_Control.Controls.Count;

                for (int i = 0; i <= l - 1; i++)
                {

                    string v_strTypeName = this.Panel_Add_Control.Controls[i].GetType().ToString();
                    string v_FieldName = "";
                    switch (v_strTypeName)
                    {
                        case "System.Windows.Forms.TextBox": //TXT#"

                            v_FieldName = this.Panel_Add_Control.Controls[i].Name.ToString();
                            v_FieldName = v_FieldName.Replace("TXT#", "");
                            rowValue[v_FieldName] = this.Panel_Add_Control.Controls[i].Text;
                            rowDataType[v_FieldName] = "T";
                            break;
                        case "System.Windows.Forms.ComboBox": //CBB#

                            v_FieldName = this.Panel_Add_Control.Controls[i].Name.ToString();
                            v_FieldName = v_FieldName.Replace("CBB#", "");

                            // nếu combobox lấy theo ID từ 1 bảng khác thì kiểm tra
                            if (this.Panel_Add_Control.Controls[i].AccessibleName != "" && this.Panel_Add_Control.Controls[i].AccessibleName.ToLower().Contains("allcode") == true)
                            {
                                // ta đã có ID theo dữ liệu truyền vào ,  Có combobox gồm tên trường nhưng ko có ID . h cần so sánh để hiện ra tên trường theo ID
                                DataTable _tableAllCode = _code._services.GetDatatable_BySQL(this.Panel_Add_Control.Controls[i].AccessibleName);
                                foreach (DataRow row in _tableAllCode.Rows)
                                {
                                    if (this.Panel_Add_Control.Controls[i].Text == row["display"].ToString())
                                    {
                                        rowValue[v_FieldName] = row["value"].ToString();
                                    }
                                }
                            }
                            else
                            {
                                rowValue[v_FieldName] = this.Panel_Add_Control.Controls[i].Text;
                            }
                            //rowValue[v_FieldName] = this.Panel_Add_Control.Controls[i].Text;
                            rowDataType[v_FieldName] = "T";

                            break;
                        case "System.Windows.Forms.DateTimePicker": //DTP#

                            v_FieldName = this.Panel_Add_Control.Controls[i].Name.ToString();
                            v_FieldName = v_FieldName.Replace("DTP#", "");
                            rowValue[v_FieldName] = DateTime.ParseExact(this.Panel_Add_Control.Controls[i].Text, "dd/MM/yyyy", CultureInfo.InvariantCulture).ToString("dd/MM/yyyy");
                            rowDataType[v_FieldName] = "D";

                            break;
                    }

                }
                TBL_RePortFLD.Rows.Add(rowValue);
                TBL_RePortFLD.Rows.Add(rowDataType);
                //this.gridControl2.DataSource = TBL_RePortFLD;
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "BUIL_FLD_BAO_CAO()");
                _code._services.UPDATE_LOG_FILE("ERR", Code.StaticVariable.userID, "Forms.FrmCreateReport", "BUIL_FLD_BAO_CAO()", ex.ToString());
                return false;
            }
        }

        //button create Report
        private void btn_Tao_bao_cao_Click(object sender, EventArgs e)
        {

            /*try {
                if (BUIL_FLD_BAO_CAO())
                {
                    DataTable TBL_result = new DataTable();
                    TBL_result = _code._services.Excute_Store_By_ListString(GET_RPTID, TBL_RePortFLD);
                    if (TBL_result.Rows.Count<=0)
                    {
                    MessageBox.Show("Không có dữ liệu cho báo cáo","Thông báo");
                        return ;
                    }
                    Boolean rptOK = Create_RP(TBL_result);
                    if (!rptOK)
                    {
                        MessageBox.Show("Tạo báo cáo lỗi");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }*/

            try
            {
                if (BUIL_FLD_BAO_CAO())
                {
                    DataTable TBL_result = new DataTable();
                    TBL_result = _code._services.Excute_Store_By_ListString(GET_RPTID, TBL_RePortFLD);
                    if (TBL_result.Rows.Count <= 0)
                    {
                        MessageBox.Show("Không có dữ liệu cho báo cáo", "Thông báo");
                        return;
                    }
                    else
                    {
                        String _rpt_path = Code.StaticVariable.v_StartUP_Path + "\\Reports\\" + GET_RPTID;
                        if (!File.Exists(_rpt_path + ".rpt"))
                        {
                            MessageBox.Show("Không tìm thấy mẫu báo cáo", "Thông báo ");
                            TBL_result.WriteXml(_rpt_path + ".xml", XmlWriteMode.WriteSchema, true);
                            return;
                        }
                        else
                        {
                            Forms.FrmPreviewReport _frm = new Forms.FrmPreviewReport(TBL_result, GET_RPTID);
                            _frm.ShowDialog();
                        }
                    }
                    
                }
            }
            catch (Exception ex)
            {
                _code._services.UPDATE_LOG_FILE("ERR", Code.StaticVariable.userID, "Forms.FrmCreateReport", "btn_Tao_bao_cao_Click()", ex.ToString());
                MessageBox.Show(ex.Message);
            }

        }

        private void btn_Huy_Click(object sender, EventArgs e)
        {
            this.Close();
        }

    }
}
